package com.itheima.im.socket.adapter;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

import com.itheima.im.socket.R;
import com.itheima.im.socket.activity.MyApp;
import com.itheima.im.socket.bean.QQMessage;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ChatAdapter extends ArrayAdapter<QQMessage> {

	public ChatAdapter(Context context, List<QQMessage> objects) {
		super(context, 0, objects);
	}

	// 行视图的种类数
	@Override
	public int getViewTypeCount() {
		return 2; // 0 ,1
	}

	// 0发送 1接收
	// 根据数据返回指定下标的视图类型
	@Override
	public int getItemViewType(int position) {
		long me = Long.parseLong(MyApp.username);
		QQMessage msg = getItem(position);
		if (me == msg.from) {
			return 0;// 发送
		}
		return 1;// 接收
	}

	static class ViewHolder {
		@InjectView(R.id.head)
		ImageView head;
		@InjectView(R.id.time)
		TextView time;
		@InjectView(R.id.content)
		TextView content;

		public ViewHolder(View view) {
			ButterKnife.inject(this, view);
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		int type = getItemViewType(position);
		if (type == 0)// 发送
		{
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = View.inflate(getContext(), R.layout.item_chat_send, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			QQMessage msg = getItem(position);
			holder.time.setText(msg.sendTime);
			holder.content.setText(msg.content);
			return convertView;

		} else // 接收
		{

			ViewHolder holder = null;
			if (convertView == null) {
				convertView = View.inflate(getContext(), R.layout.item_chat_receive, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			QQMessage msg = getItem(position);
			holder.time.setText(msg.sendTime);
			holder.content.setText(msg.content);

			return convertView;
		}
	}

}
